package ${package}

import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.ArrayList
import java.util.Arrays
import java.util.Date
import java.util.HashMap
import java.util.List
import java.util.Map

import javax.servlet.http.HttpServletResponse

import org.apache.commons.lang3.StringUtils
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.beetl.sql.core.engine.PageQuery
import org.jxls.common.Context
import org.jxls.reader.ReaderBuilder
import org.jxls.reader.ReaderConfig
import org.jxls.reader.XLSReadMessage
import org.jxls.reader.XLSReadStatus
import org.jxls.reader.XLSReader
import org.jxls.util.JxlsHelper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.ModelAndView

import com.ibeetl.admin.console.web.dto.DictExcelImportData
import com.ibeetl.admin.console.web.query.UserQuery
import com.ibeetl.admin.core.annotation.Function
import com.ibeetl.admin.core.annotation.Query
import com.ibeetl.admin.core.entity.CoreDict
import com.ibeetl.admin.core.entity.CoreUser
import com.ibeetl.admin.core.file.FileItem
import com.ibeetl.admin.core.file.FileService
import com.ibeetl.admin.core.web.JsonResult
import com.ibeetl.admin.core.util.*
import ${basePackage}.entity.*
import ${basePackage}.service.*
import ${basePackage}.web.query.*
import javax.annotation.Resource

/**
 * ${entity.displayName} 接口
 */
\@Controller
class ${entity.name}Controller{

    companion object{
        const val MODEL = "/${target.urlBase}/${entity.code}";
    }

    private val log = LogFactory.getLog(this.javaClass)

    @var service=entity.code+"Service";

    \@Resource
    private lateinit var ${service}:${entity.name}Service
    
    \@Resource
    private lateinit var fileService:FileService

    /* 页面 */

    \@GetMapping("$MODEL/index.do")
    \@Function("${basicfunctionCode}.query")
    \@ResponseBody
    fun index(): ModelAndView {
        val view = ModelAndView("/${target.urlBase}/${entity.code}/index.html")
        view.addObject("search", ${entity.name}Query::class.java.getName())
        return view
    }

    \@GetMapping("$MODEL/edit.do")
    \@Function("${basicfunctionCode}.edit")
    \@ResponseBody
    fun edit(${entity.idAttribute.name}: ${entity.idAttribute.javaType}): ModelAndView {
        val view = ModelAndView("/${target.urlBase}/${entity.code}/edit.html")
        val ${entity.code}: ${entity.name} = ${service}.queryById(${entity.idAttribute.name})
        view.addObject("${entity.code}", ${entity.code})
        return view
    }

    \@GetMapping("$MODEL/add.do")
    \@Function("${basicfunctionCode}.add")
    \@ResponseBody
    fun add(): ModelAndView {
        val view = ModelAndView("/${target.urlBase}/${entity.code}/add.html")
        return view
    }

    /* ajax json */

    \@PostMapping("$MODEL/list.json")
    \@Function("${basicfunctionCode}.query")
    \@ResponseBody
    fun list(condtion: ${entity.name}Query ): JsonResult<PageQuery<*>>{
        val page = condtion.pageQuery
        ${service}.queryByCondition(page)
        return JsonResult.success(page)
    }

    \@PostMapping("$MODEL/add.json")
    \@Function("${basicfunctionCode}.add")
    \@ResponseBody
    fun add(\@Validated(ValidateConfig.ADD::class) ${entity.code}: ${entity.name}): JsonResult<Any>{
        ${service}.save(${entity.code})
        return JsonResult.success()
    }

    \@PostMapping("$MODEL/edit.json")
    \@Function("${basicfunctionCode}.edit")
    \@ResponseBody
    fun update(\@Validated(ValidateConfig.UPDATE::class) ${entity.code}: ${entity.name}): JsonResult<String> {
        val success = ${service}.update(${entity.code})
        if (success) {
            return JsonResult.success()
        } else {
            return JsonResult.failMessage("保存失败")
        }
    }


   
    \@GetMapping("$MODEL/view.json")
    \@Function("${basicfunctionCode}.query")
    \@ResponseBody
    fun queryInfo(${entity.idAttribute.name}: ${entity.idAttribute.javaType}): JsonResult<${entity.name}> {
        val ${entity.code}: ${entity.name} = ${service}.queryById(${entity.idAttribute.name})
        return JsonResult.success(${entity.code})
    }

    \@PostMapping("$MODEL/delete.json")
    \@Function("${basicfunctionCode}.delete")
    \@ResponseBody
    fun delete(ids_: String): JsonResult<Any> {
        var ids = ids_
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",")
        }
        val idList = ConvertUtil.str2longs(ids)
        ${service}.batchDel${entity.name}(idList)
        return JsonResult.success()
    }
    
    @if(entity.includeExcel){
    
    \@PostMapping("$MODEL/excel/export.json")
    \@Function("${basicfunctionCode}.export")
    \@ResponseBody
    fun export(response: HttpServletResponse, condtion: ${entity.name}Query): JsonResult<String> {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此${service}.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        val excelTemplate ="excelTemplates/${target.urlBase}/${entity.code}/你的excel模板文件名字.xls"
        val page = condtion.getPageQuery()
        //取出全部符合条件的
        page.setPageSize(Int.MAX_VALUE)
        page.setPageNumber(1)
        page.setTotalRow(Int.MAX_VALUE)
        //本次导出需要的数据
        val list: List<${entity.name}> = ${service}.queryByCondition(page).getList()
        Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate).use{
            val item = fileService.createFileTemp("${entity.displayName}_"+DateUtil.now("yyyyMMddHHmmss")+".xls")
            val os = item.openOutpuStream()
            val context = Context()
            context.putVar("list", list)
            JxlsHelper.getInstance().processTemplate(it, os, context)
            os.close()
            //下载参考FileSystemContorller
            return JsonResult.success(item.getPath())
        }
    }
    
    \@PostMapping("$MODEL/excel/import.do")
    \@Function("${basicfunctionCode}.import")
    \@ResponseBody
    fun importExcel(\@RequestParam("file") file: MultipartFile): JsonResult<Any> {
        if (file.isEmpty()) {
           return JsonResult.fail()
        }
        val ins = file.getInputStream()
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close()
        return JsonResult.success()
    }
    
    
    @}

}
